<template>
  <a-space direction="vertical" style="width: 100%">
    <a-page-header
        style="border: 1px solid rgb(235, 237, 240)"
        title="用户注册"
        @back="() => $router.push('/')"
    />
    <div class="inform">
      <a-form
          :model="formState"
          name="userlogister"
          @validate="handleValidate"
          :rules="rules"
      >
        <a-form-item label="头像">
          <a-upload
              name="file"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              action="/user/upload/file"
              :before-upload="beforeUpload"
              @change="handleChange"
          >
            <img v-if="imageUrl" :src="imageUrl" alt="avatar"/>
            <div v-else>
              <loading-outlined v-if="loading"></loading-outlined>
              <plus-outlined v-else></plus-outlined>
              <div class="ant-upload-text">Upload</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item has-feedback label="登陆名" name="userName">
          <a-input v-model:value="formState.userName"/>
        </a-form-item>
        <a-form-item has-feedback label="密码" name="password">
          <a-input v-model:value="formState.password" type="password" autocomplete="off"/>
        </a-form-item>
        <a-form-item has-feedback label="确认密码" name="checkPass">
          <a-input v-model:value="formState.checkPass" type="password" autocomplete="off"/>
        </a-form-item>
        <a-form-item label="昵称" name="name">
          <a-input v-model:value="formState.name"/>
        </a-form-item>
        <a-form-item label="性别">
          <a-radio-group v-model:value="formState.sex">
            <a-radio :value="0">男</a-radio>
            <a-radio :value="1">女</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="Email" name="email">
          <a-input v-model:value="formState.email"/>
        </a-form-item>
        <a-space :size="20">
          <a-form-item has-feedback label="年龄" name="age">
            <a-input-number v-model:value="formState.age"/>
          </a-form-item>
          <a-form-item :name="formState.birthday" label="生日"
                       :rules="[{type: 'array',required: true, message: 'Please select time!',}]">
            <a-date-picker v-model:value="formState.birthday" value-format="YYYY-MM-DD"/>
          </a-form-item>
        </a-space>
        <a-form-item name="website" label="个人网站">
          <a-input v-model:value="formState.website"/>
        </a-form-item>
        <a-form-item name="introduction" label="个人简介">
          <a-textarea :rows="4" :showCount="true" v-model:value="formState.introduction"/>
        </a-form-item>
        <a-form-item>
          <a-space :size="64">
            <a-button type="primary" @click="submit" :disabled="disabled">提交</a-button>
            <a-button type="primary" @click="back">取消</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>
  </a-space>
</template>

<script>
import {computed, onMounted, reactive, ref} from "vue";
import store from "@/store";
import router from "@/router";
import axios from "axios";
import {message, notification} from "ant-design-vue";

export default {
  name: "register",
  setup() {
    const user = computed(() => store.state.user)
    const formState = reactive({
      userName: '',
      name: '',
      password: '',
      checkPass: '',
      sex: 0,
      age: undefined,
      email: '',
      website: '',
      birthday: '',
      introduction: '',
      photo: ''
    })

    // const layout = {
    //   labelCol: {
    //     span: 8,
    //   },
    //   wrapperCol: {
    //     span: 16,
    //   },
    // };


    //头像框
    const imageUrl = ref('');
    const loading = ref(false);
    const handleChange = info => {
      if (info.file.status === 'uploading') {
        loading.value = true;
        console.log("uping", info)
        return;
      }
      if (info.file.status === 'done') {
        console.log("done", info)
        // Get this url from response in real world.
        // getBase64(info.file.originFileObj, base64Url => {
        //   formState.photo = base64Url;
        //   user.value.photo = base64Url;
        //   imageUrl.value=base64Url;
        //   loading.value = false;
        // });
        imageUrl.value = info.file.response.content;
        formState.photo = info.file.response.content;
        loading.value = false;
        console.log("上传完图片,info", info.file.response.content)
        console.log("上传完图片,formstate", formState)
      }
      if (info.file.status === 'error') {
        loading.value = false;
        message.error('upload error');
      }
    };
    const beforeUpload = file => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('You can only upload JPG file!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
      }
      return isJpgOrPng && isLt2M;
    };

    const back = () => {
      router.push('/')
    }

    const formRef = ref();

    let validatePass = async (_rule, value) => {
      if (value.length < 6) {
        return Promise.reject('密码必须大于6位');
      } else {
        if (formState.checkPass !== '') {
          await formRef.value.validateFields('checkPass');
        }
        return Promise.resolve();
      }
    };

    let validatePass2 = async (_rule, value) => {
      if (value === '') {
        return Promise.reject('Please input the password again');
      } else if (value !== formState.password) {
        return Promise.reject("Two inputs don't match!");
      } else {
        return Promise.resolve();
      }
    };

    let checkAge = async (_rule, value) => {
      if (!value) {
        return Promise.reject('请输入年龄');
      }

      if (!Number.isInteger(value)) {
        return Promise.reject('请输入数字');
      } else {
        if (value < 0 || value > 100) {
          return Promise.reject('Age必须大于0或者小于100');
        } else {
          return Promise.resolve();
        }
      }
    };

    const disabled = computed(() => {
      return !(formState.userName && formState.password && formState.name && formState.checkPass);
    });

    const rules = {
      userName: [{
        required: true,
        message: "登录名必须填写",
        trigger: 'change',
      }],
      password: [{
        required: true,
        // pattern:"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,32}$",
        validator: validatePass,
        trigger: 'change',
      }],
      checkPass: [{
        validator: validatePass2,
        trigger: 'change',
      }],
      name: [{
        required: true,
        message: "昵称必须填写",
        trigger: 'change',
      }],
      age: [{
        validator: checkAge,
        trigger: 'change',
      }],
      email: [{
        type: 'email',
        message: "请输入正确的邮箱格式"
      }]
    };

    const handleValidate = (...args) => {
      console.log(args);
    };

    // async function submit(){
    //   let res = await axios.post('/user/insert'+formState)
    // }
    const openNotificationWithIcon = str => {
      notification['success']({
        message: '注册成功',
        description: '欢迎你，' + str,
      });
    };

    const submit = () => {
      console.log(formState);
      axios.post("/user/insert", formState).then((res) => {
        if (res.data.status === 10000) {
          // message.success("注册成功，欢迎"+res.data.content.name);
          openNotificationWithIcon(res.data.content.name);
          const data = res.data;
          store.commit("setUser", data.content);
          router.push('/')
        } else {
          message.error(data.message);
        }
      })
    }

    onMounted(() => {
      // console.log(formState)
    })

    return {
      imageUrl,
      user,
      loading,
      handleChange,
      beforeUpload,
      formState,
      rules,
      // layout
      handleValidate,
      back,
      submit,
      disabled
    }
  }
}
</script>

<style scoped>
.inform {
  width: 80%;
  height: 80%;
  margin-left: 10%;
}

img {
  width: 100px;
  height: 100px;
}

.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>